/* 
	
CODE TO PRODUCE FIGURES

Figures produced in this code:

Figure 1
Figure 2
Figure 3
Figure 4
Figure 5 (estimates only - figure is created in excel)
Figure 6
Figure 7
Figure 8
Figure 9
Figure 10
Figure 11
Figure 12

Appendix Figure A1
Appendix Figure A2
Appendix Figure A3
Appendix Figure A4
Appendix Figure A5
Appendix Figure A6
Appendix Figure A7
Appendix Figure B1
Appendix Figure B2
Appendix Figure B3
Appendix Figure B4
Appendix Figure C1
Appendix Figure D1
Appendix Figure D2
Appendix Figure D3
Appendix Figure D4

*/

********************************************************************************
* set directories
********************************************************************************
global input = "..\Input_data\" // set path for data/input files
global out = "..\Output\" // set path for output (tables/figures)

********************************************************************************
* Settings
********************************************************************************
global bw10 "inrange(r,-12,10) & donut==0" 
global bw8 "inrange(r,-10,8) & donut==0" 
global bw6 "inrange(r,-8,6) & donut==0" 

********************************************************************************
** PROGRAMS USED TO CREATE FIGURES
********************************************************************************
*-------------------------------------------------------------------------------
* PROGRAM FOR IQ-BASED RD PLOTS (means + 95% CI's + fitted lines for 3 bw's): 
*-------------------------------------------------------------------------------
cap program drop rdplot3bw
program define rdplot3bw
args dep smpl lb delta ub format leg
 /* program takes 7 arguments:
	dep: outcome 
	smpl: subgroup indicator (all=pooled, m=boys, f=girls, etc.)
	NOTE: smpl also sets figure subtitles; use m_alt, f_alt for titles without letters A/B
	lb, delta, ub: y-axis range 
	format: format of the y-axis label 
	leg: leg or noleg --> whether or not to include a legend
 */	

* set graph scheme 
set scheme modern 

preserve 
	* keep relevant sample (all, boys, girls)
	keep if `smpl'==1 
	
	* rescaled running variable for figure
	gen x = r + 116

	* add fake obs 
	count 
	forval n=1(1)3 {
		local n`n' = `r(N)'+`n'
	}
	set obs `n3'
	replace x=115.9 in `n1'
	replace x=113.5 in `n2'
	replace x=116.5 in `n3'
	replace r=x-116 if r==.
	replace d=(r>=0) if d==.
	replace dxr=d*r if dxr==.
	replace donut = inrange(x,113.45,116.55)
	gen fake = 0
	replace fake = 1 in `n1'/`n3' 

	* linear regressions for each bw
	forval bw=6(2)10 {
	    reg `dep' r d dxr if ${bw`bw'} 
		predict yhat_bw`bw' 
	}

	* collapse data
	collapse (mean) donut fake m=`dep' yhat_bw* (sd) sd=`dep' (count) n=`dep', by(x)	
	gen se = sd/sqrt(n-1) 
	gen lower = m-1.96*se 
	gen upper = m+1.96*se
	gen r_lower = `lb'
	gen r_upper = `ub'

	* figure titles:
	if "`smpl'"=="all" {
			local title = ""
			}
	if "`smpl'"=="m" {
			local title = "A. Boys"
		}
	if "`smpl'"=="m_alt" {
			local title = "Boys"	
			}
	if "`smpl'"=="f" {
			local title = "B. Girls"
			}
	if "`smpl'"=="f_alt" {
			local title = "Girls"
		}
	if "`smpl'"=="hi" {
			local title = "High Enjoyment"
			}
	if "`smpl'"=="lo" {
			local title = "Lower Enjoyment"
		}	
	
	* legend options:
	if "`leg'"=="leg" { 		
		twoway (rarea r_lower r_upper x if (inrange(x,113.45,116.55)), lc(gs8%20) lw(thin) fc(gs10%15)) ///
			(line yhat_bw10 x if (inrange(x,104,115.95)), lc(red) lw(medthick)) ///
			(line yhat_bw8 x if (inrange(x,106,115.95)), lc(green) lw(thick)) ///
			(line yhat_bw6 x if (inrange(x,108,115.95)), lc(gold) lw(medthick)) ///
			(line yhat_bw10 x if (inrange(x,116,126)) & fake==0, lc(red) lw(medthick)) ///
			(line yhat_bw8 x if (inrange(x,116,124)) & fake==0, lc(green) lw(thick)) ///
			(line yhat_bw6 x if (inrange(x,116,122)) & fake==0, lc(gold) lw(medthick)) ///			
			(scatter m x if (inrange(x,100,130) & donut==0), mc(blue) ms(o)) ///
			(scatter m x if (inrange(x,100,130) & donut==1), mc(gs12) ms(o)) ///
			(scatter m x if (inrange(x,100,130)), mc(gs8) mlw(thin) ms(oh) ) ///
			(rline lower upper x if (inrange(x,100,130)), lc(emidblue) lw(thin)) ///
			, leg(order(2 "local linear, bw=10" 3 "local linear, bw=8" 4 "local linear, bw=6") r(3) ring(0) pos(10)) ///
			xline(116, lc(gs12) lw(medthick) lp("-")) xlabel(100 105 to 125, nogrid)  ///
			ylabel(`lb'(`delta')`ub', angle(0) format(%`format'fc) axis(1) glcolor(gray*.15) glpattern(dash)) ///
			yti("") xti("IQ Score") ti("`title'", size(*1.1)) name(`dep'_`smpl', replace)
	}
	if "`leg'"=="noleg" { 		
		twoway (rarea r_lower r_upper x if (inrange(x,113.45,116.55)), lc(gs8%20) lw(thin) fc(gs10%15)) ///
			(line yhat_bw10 x if (inrange(x,104,115.95)), lc(red) lw(medthick)) ///
			(line yhat_bw8 x if (inrange(x,106,115.95)), lc(green) lw(thick)) ///
			(line yhat_bw6 x if (inrange(x,108,115.95)), lc(gold) lw(medthick)) ///
			(line yhat_bw10 x if (inrange(x,116,126)) & fake==0, lc(red) lw(medthick)) ///
			(line yhat_bw8 x if (inrange(x,116,124)) & fake==0, lc(green) lw(thick)) ///
			(line yhat_bw6 x if (inrange(x,116,122)) & fake==0, lc(gold) lw(medthick)) ///			
			(scatter m x if (inrange(x,100,130) & donut==0), mc(blue) ms(o)) ///
			(scatter m x if (inrange(x,100,130) & donut==1), mc(gs12) ms(o)) ///
			(scatter m x if (inrange(x,100,130)), mc(gs8) mlw(thin) ms(oh) ) ///
			(rline lower upper x if (inrange(x,100,130)), lc(emidblue) lw(thin)) ///
			, leg(off) ///
			xline(116, lc(gs12) lw(medthick) lp("-")) xlabel(100 105 to 125, nogrid)  ///
			ylabel(`lb'(`delta')`ub', angle(0) format(%`format'fc) axis(1) glcolor(gray*.15) glpattern(dash)) ///
			yti("") xti("IQ Score") ti("`title'", size(*1.1)) name(`dep'_`smpl', replace) 
	}
	
end

*-------------------------------------------------------------------------------
* PROGRAM FOR BAR CHART WITH GIFTED & NON-GIFTED COMPLIER MEANS (bw=8): 
*-------------------------------------------------------------------------------
	cap program drop barcompy0y1
	program define barcompy0y1
	args dep lb delta ub trim  
	/* program takes 5 arguments:
		dep: outcome 
		lb, delta, ub: y-axis range 
		trim: trim y axis
	*/	

	* set graph scheme 
	set scheme modern 
	
	cap gen notgifted = 1 - gifted
	cap drop `dep'_x_notgifted 
	cap drop `dep'_x_gifted 
	cap gen `dep'_x_notgifted = `dep'*notgifted
	cap gen `dep'_x_gifted = `dep'*gifted

	* estimate male complier outcomes
	*- non-gifted compliers
	xi: ivreg `dep'_x_notgifted (notgifted = d r dxr) r dxr if ${bw8} & m==1, cluster(schid)
	local complier_y0_m = _b[notgifted]
	local se_y0_m = _se[notgifted]
	*- gifted compliers
	xi: ivreg `dep'_x_gifted (gifted = d r dxr) r dxr if ${bw8} & m==1, cluster(schid)
	local complier_y1_m = _b[gifted]
	local se_y1_m = _se[gifted]

	* estimate female complier outcomes
	*- non-gifted compliers
	xi: ivreg `dep'_x_notgifted (notgifted = d r dxr) r dxr if ${bw8} & f==1, cluster(schid)
	local complier_y0_f = _b[notgifted]
	local se_y0_f = _se[notgifted]
	*- gifted compliers
	xi: ivreg `dep'_x_gifted (gifted = d r dxr) r dxr if ${bw8} & f==1, cluster(schid)
	local complier_y1_f = _b[gifted]
	local se_y1_f = _se[gifted]

	preserve

		* store results as a separate file
		clear 
		set obs 4 // four bars
		gen n=_n

		seq group, f(1) t(2)
		 // complier untreated and complier treated outcomes

		gen male = (_n==1 | _n==2)
		gen female = (_n==3 | _n==4)

		* variables for each group and standard errors
		gen y = . 
		gen se = .

		replace y = `complier_y0_m' if m==1 & group==1
		replace y = `complier_y0_f' if f==1 & group==1
		replace se = `se_y0_m' if m==1 & group==1 // standard error
		replace se = `se_y0_f' if f==1 & group==1 // standard error

		replace y = `complier_y1_m' if m==1 & group==2
		replace y = `complier_y1_f' if f==1 & group==2
		replace se = `se_y1_m' if m==1 & group==2 // standard error
		replace se = `se_y1_f' if f==1 & group==2 // standard error

		gen y_upper = y+1.96*se
		gen y_lower = y-1.96*se

		if "`trim'"=="trim" {
			replace y = 1 if y>1
			replace y = 0 if y<0
			replace y_upper = 1 if y_upper>1
			replace y_lower = 0 if y_lower<0
		}

		replace n = n+1 if _n>2
		* figure
		graph twoway (bar y n if group==1, fc(gs12) lc(gs8))  ///
		 (bar y n if group==2, fc(edkblue*.70) lc(edkblue)) ///
		 (rcap y_upper y_lower n if group==1, lcolor(gs8) lwidth(vthin)) ///
		 (rcap y_upper y_lower n if group==2, lcolor(edkblue) lwidth(vthin)), ///
		 legend(order (1 "Untreated (Not Gifted)" 2 "Treated (Gifted)") region(lcolor(white))) ///
		 xlabel(1.5 "Male Compliers" 4.5 "Female Compliers", noticks) ///
		 ytitle("") ///
		 ylabel(`lb'(`delta')`ub') xtitle("") ///
		 title("") ///
		 scheme(s2color) ///
		 graphregion(color(white) fcolor(white) icolor(white) ifcolor(white) lcolor(white) ilcolor(white)) ///
		 plotregion(color(white) fcolor(white) icolor(white) ifcolor(white) lcolor(white) ilcolor(white))  ///
		 name(bar_`dep', replace)
	 
	restore
	
end	


************************************************************************************
** APPENDIX FIG A1. MALE-FEMALE RATIO OF COLLEGE STUDENTS BY FAMILY INCOME QUARTILE
************************************************************************************
{
	/* 
		Source for estimates: U.S. Department of Education, National Center for Education Statistics, 
		1995-96 National Postsecondary Student Aid Study (NPSAS:96), NPSAS:2000, NPSAS:04, NPSAS:08,
		NPSAS:12 and NPSAS:16. Computation by NCES TrendStats on 8/28/2021.
	*/
	set scheme modern 
	clear 
	set obs 4 
	gen quartile = _n 
	label define qlbl 1 "Quartile 1" 2 "Quartile 2" 3 "Quartile 3" 4 "Quartile 4"
	label val quartile qlbl
	gen ratio = .606 in 1
	replace ratio = .713 in 2
	replace ratio = .859 in 3 
	replace ratio = 1.011 in 4
	graph hbar ratio, over(quartile, relabel(1 "Quartile 1" 2 "Quartile 2" 3 "Quartile 3" 4 "Quartile 4")) ///
		yti("Male-Female Ratio of College Students") ylab(, format(%9.1f)) scale(*1.2)
	graph export "${out}fig_A1.png", replace
}


********************************************************************************
** FIG 1. COLLEGE ENTRY BY GR 2 INDEX, GENDER, FRL (3 cohorts, all non-gifted)
********************************************************************************
{
	
set scheme modern

use "${input}figure1.dta", clear

* Local polynomial smooth plots for on-time college entry vs. predicted outcome - 4 groups gender X FRL (non-gifted only)
twoway	(lpolyci collot prcollot  if f==1 & frl==0, lc(maroon*.80) fc(maroon%50) lw(medthick) lp(l) bw(.45) degree(1) kernel(biweight)) ///
		(lpolyci collot prcollot  if f==1 & frl==1, lc(orange*.90) fc(orange%60) lw(medthick) lp("_") bw(.45) degree(1) kernel(biweight) ) ///
		(lpolyci collot prcollot  if f==0 & frl==0, lc(navy*.80) fc(navy%50) lw(medthick) lp("-") bw(.45) degree(1) kernel(biweight)) ///		
		(lpolyci collot prcollot  if f==0 & frl==1, lc(green*.95) fc(green%70) lw(medthick) lp("_-") bw(.45) degree(1) kernel(biweight) ) ///
		if inrange(prcollot,.3,.9) & gifted==0 ///
		, xti("Index of Cognitive Ability & Achievement in Grade 2") yti("Pr(Graduate On Time & Enter College)") ///
		xline(.78 .72 .81) xlab(.3 .4 to .9) ylab(0 .1 to 1) scheme(modern) ///
		leg(order(1 "" 2  "Non-FRL Girls" 3 "" 4 "FRL Girls" 5 "" 6 "Non-FRL Boys" 7 "" 8  "FRL Boys") r(4) ring(0) pos(10)) 
	graph export "${out}fig_1.png", replace

}


********************************************************************************
** FIG 2. HISTOGRAM OF RUNNING VARIABLE (with donut obs in lighter shade)
******************************************************************************** 
{
	
	use "${input}planb_rdsmpl.dta", clear
	gen x = r+116

	* Panel A - boys only 
	graph twoway (hist x if m==1, discrete freq xti("IQ Score") fcolor(emidblue*0.2) lcolor(emidblue*0.6)) ///	
		(hist x if donut==0 & m==1, discrete freq xti("IQ Score") fcolor(navy*0.4) lcolor(navy*0.8)) ///
		(scatteri 0 115.5 250 115.5, c(l) m(i) lc(black*0.5) lp("dash")) ///
		, ylabel(, angle(0) format(%9.0fc) axis(1) glcolor(gray*.15) glpattern(dash)) xlab(100 105 to 125, glcolor(none)) ///
		graphregion(color(white) fcolor(white) icolor(white) ifcolor(white) lcolor(white) ilcolor(white)) ///
		plotregion(color(white) fcolor(white) icolor(white) ifcolor(white) lcolor(white) ilcolor(white)) ///
		legend(off) ti("A. Boys", size(*1.1)) name(hist_boys, replace)
	 graph display hist_boys, ysize(2.75) xsize(3.8) scale(*1.2)	
	graph export "${out}fig_2a.png", replace

	* Panel B - girls only 
	graph twoway (hist x if f==1, discrete freq xti("IQ Score") fcolor(emidblue*0.2) lcolor(emidblue*0.6)) ///	
		(hist x if donut==0 & f==1, discrete freq xti("IQ Score") fcolor(navy*0.4) lcolor(navy*0.8)) ///
		(scatteri 0 115.5 250 115.5, c(l) m(i) lc(black*0.5) lp("dash")) ///
		, ylabel(, angle(0) format(%9.0fc) axis(1) glcolor(gray*.15) glpattern(dash)) xlab(100 105 to 125, glcolor(none)) ///
		graphregion(color(white) fcolor(white) icolor(white) ifcolor(white) lcolor(white) ilcolor(white)) ///
		plotregion(color(white) fcolor(white) icolor(white) ifcolor(white) lcolor(white) ilcolor(white)) ///
		legend(off) ti("B. Girls", size(*1.1)) name(hist_girls, replace)
	 graph display hist_girls, ysize(2.75) xsize(3.8) scale(*1.2)	
	graph export "${out}fig_2b.png", replace

}

********************************************************************************
** FIG 3. FIRST STAGE (gifted status vs. first IQ score) 
********************************************************************************
{
	use "${input}planb_rdsmpl.dta", clear
	
	global gifted_set = "0 .2 1 9.1"	// settings for y-axis 
	foreach var of varlist gifted {	
		rdplot3bw `var' m $`var'_set leg
		rdplot3bw `var' f $`var'_set leg	
	}	
	graph display gifted_m, ysize(2.7) xsize(3.8) scale(*1.4)
		graph export "${out}fig_3a.png", replace
	graph display gifted_f, ysize(2.7) xsize(3.8) scale(*1.4)
		graph export "${out}fig_3b.png", replace

}

********************************************************************************
** FIG 4. ON TIME HS GRAD AND COLLEGE ENTRY, OBSERVED vs. PREDICTED
********************************************************************************
{
	use "${input}planb_rdsmpl.dta", clear

	gen m_alt = m  // sample flags for alternate figure titles in rdplot3bw
	gen f_alt = f

	* for figure with 4 panels: observed/predicted, boys/girls (with legend)
	global collot_set = ".3 .1 1 9.1"
	global pr_collot_set = ".3 .1 1 9.1"
	foreach var of varlist collot pr_collot {	
		rdplot3bw `var' m_alt $`var'_set leg
		rdplot3bw `var' f_alt $`var'_set leg	
	}
		graph display collot_m_alt, ysize(2.7) xsize(3.8) scale(*1.4) 
		graph export "${out}fig_4a_m.png", replace
		graph display collot_f_alt, ysize(2.7) xsize(3.8) scale(*1.4)
		graph export "${out}fig_4a_f.png", replace
		graph display pr_collot_m_alt, ysize(2.7) xsize(3.8) scale(*1.4)
		graph export "${out}fig_4b_m.png", replace
		graph display pr_collot_f_alt, ysize(2.7) xsize(3.8) scale(*1.4)
		graph export "${out}fig_4b_f.png", replace

}

********************************************************************************
** FIG 5. BANDWIDTH SENSITIVITITY 
********************************************************************************
{
	
	** Figure was created in Excel based on the estimates in outputted matrice
	** See figure_5.xlsx
	
	use "${input}planb_rdsmpl.dta", clear
	
	local bw_l_list 3 4 5 6 7 8 9 10 11 12 13 14    // left bandwidths
	local bw_r_list 3 4 5 6 7 8 9 10 11 12          // right bandwidths
	local nL : word count `bw_l_list'
	local nR : word count `bw_r_list'

	foreach sex in m f {
		
    matrix b_`sex'  = J(`nL', `nR', .)
    matrix se_`sex' = J(`nL', `nR', .)
	
	local i = 1
	foreach bw_l of local bw_l_list {
        local j = 1
        foreach bw_r of local bw_r_list {

            quietly regress collot r d dxr ///
                if donut==0 ///
                & inrange(r, -2-`bw_l', `bw_r') ///
                & `sex'==1, cluster(schid)

            matrix b_`sex'[`i',`j']  = _b[d]

            local ++j
        }
        local ++i
    }
	matrix rownames b_`sex'  = `bw_l_list'
    matrix colnames b_`sex'  = `bw_r_list'
	}
	
	matrix list b_m
	matrix list b_f 

}	

	
************************************************************************************
** APPENDIX FIG A2. TIMING OF GIFTED SCREENING, IDENTIFICATION, & RELEVANT PROGRAMS
************************************************************************************
{
	use "${input}appendix_figure_a2.dta", clear
	graph bar, over(min_grade_gifted)
	graph export "${out}fig_A2.png", replace
	
}


********************************************************************************
** APP FIG A3. PREDICTED ON-TIME COLLEGE ENTRY USING 2nd GRADE SAT OR NNAT
********************************************************************************
{
	
	use "${input}planb_rdsmpl.dta", clear

	gen m_alt = m  // sample flags for alternate figure titles in rdplot3bw
	gen f_alt = f

	* for figure with 4 panels: observed/predicted, boys/girls (with legend)
	global pr_collot_g2sat_set = ".3 .1 1 9.1"
	global pr_collot_g2nai_set = ".3 .1 1 9.1"
	foreach var of varlist pr_collot_g2sat pr_collot_g2nai {	
		rdplot3bw `var' m_alt $`var'_set leg
		rdplot3bw `var' f_alt $`var'_set leg	
	}
		graph display pr_collot_g2sat_m_alt, ysize(2.667) xsize(4) scale(*1.2) 
		graph export "${out}fig_A3a_m.png", replace
		graph display pr_collot_g2sat_f_alt, ysize(2.667) xsize(4) scale(*1.2) 
		graph export "${out}fig_A3a_f.png", replace
		graph display pr_collot_g2nai_m_alt, ysize(2.667) xsize(4) scale(*1.2) 
		graph export "${out}fig_A3b_m.png", replace
		graph display pr_collot_g2nai_f_alt, ysize(2.667) xsize(4) scale(*1.2)
		graph export "${out}fig_A3b_f.png", replace

}

********************************************************************************
*** FIG. 6. BAR CHART FIGURE WITH COMPLIER MEANS (LOCAL LINEAR, BW=8)
********************************************************************************
{
	use "${input}planb_rdsmpl.dta", clear
	barcompy0y1 collot 0 .25 1
	graph display bar_collot, ysize() xsize() scale(*1.1)
	graph export "${out}fig_6.png", replace

}

********************************************************************************
*** FIG. 7. BAR CHARTS WITH COMPLIER MEANS - BY GR 3 ENJOYMENT OF LEARNING ***
********************************************************************************
{
	use "${input}planb_rdsmpl.dta", clear
	
	cap drop hi lo 
	rename enjoy_g3 hi
	gen lo = 1-hi 

	foreach smp in lo hi {
		gen collot_`smp' = collot if `smp'==1
		barcompy0y1 collot_`smp' 0 .2 1 trim
		graph display bar_collot_`smp', ysize(3.4) xsize(4.6) scale(*1.1)	
		graph export "${out}fig_7_`smp'.png", replace
	}
}

********************************************************************************
*** APP FIG. A4. FIRST STAGE & REDUCED FORM FIGURES 
*** BOYS & GIRLS & POOLED, BY GRADE 3 ENJOYMENT OF LEARNING  
********************************************************************************
{
	global gifted_set = "0 .2 1 9.1"	// settings for y-axis 
	global collot_set = ".3 .1 1 9.1"

	use "${input}planb_rdsmpl.dta", clear

	cap drop hi lo 
	rename enjoy_g3 hi
	gen lo = 1-hi 

	foreach dep in gifted collot {
		foreach smpl in lo hi {
			rdplot3bw `dep' lo ${`dep'_set} leg
			rdplot3bw `dep' hi ${`dep'_set} leg
		}
	}
	graph display gifted_lo, ysize(2.5) xsize(3.6) scale(*1.2)
	graph export "${out}fig_A4a_lo.png", replace
	graph display gifted_hi, ysize(2.5) xsize(3.6) scale(*1.2)
	graph export "${out}fig_A4a_hi.png", replace
	graph display collot_lo, ysize(2.5) xsize(3.6) scale(*1.2)
	graph export "${out}fig_A4b_lo.png", replace
	graph display collot_hi, ysize(2.5) xsize(3.6) scale(*1.2)
	graph export "${out}fig_A4b_hi.png", replace
}

********************************************************************************
*** APP FIG. A5. HETEROGENEITY COEFFICIENT PLOT (LOCAL LINEAR, BW=8) *****
********************************************************************************
{
	
use "${input}appendix_figure_a5.dta", clear

* pooled sample flag 
gen all=1

* clear any previous results
estimates clear

* set scheme and color for girls
set scheme s2color 
local fcolor "orange_red"

* global for the loop used to estimate each subgroup model
global subgroups "all white  black  hispanic  frl  nonfrl  plengl  plnoneng  above_med_g3  below_med_g3  above_med_sch_zg5_m  below_med_sch_zg5_m  above_med_sch_frl  below_med_sch_frl "

* boys only heterogeneity
foreach samp in $subgroups { 
	cap drop g_`samp'
	gen g_`samp' = gifted
	xi: ivreg collot  (g_`samp' =  d r dxr) r dxr i.cohort if ${bw8} & `samp'==1 & m==1, cluster(schid)
	estimates store m_`samp'
} // end sample loop

* girls only heterogeneity
foreach samp in $subgroups { 
	cap drop g_`samp'
	gen g_`samp' = gifted
	xi: ivreg collot  (g_`samp' =  d r dxr) r dxr i.cohort if ${bw8} & `samp'==1 & f==1, cluster(schid)
	estimates store f_`samp'
} // end sample loop

estimates dir

* specify globals to format/setup the figure (created using coefplot)
global graphplot "" // global for storing the order/series of subgroup samples
global offset1 = 0.12 // global that specifies for each subgroup of boys the position of the respective coefficient plot
global offset2 = -0.12 // global that specifies for each subgroup of girls the position of the respective coefficient plot

global subgroups_for_figure = "all white  black  hispanic  frl  nonfrl  plengl  plnoneng  above_med_g3  below_med_g3  above_med_sch_frl  below_med_sch_frl  above_med_sch_zg5_m  below_med_sch_zg5_m "

foreach samp in $subgroups_for_figure {
	global graphplot = "$graphplot" + "(m_`samp', ms(o) offset($offset1) mc(blue) ciopts(lc(blue))) (f_`samp', offset($offset2) ms(dh) mc(orange_red) ciopts(lc(orange_red) ))"
}

coefplot $graphplot ///
	, keep(g_*) xlab(-.5(.25)1.0, labsize(*.8)) xline(0, lcolor(black) lpattern(dash)) ///
	legend(order(2 "Boys" 4 "Girls") rows(2) pos(3) ring(0) nobox region(lstyle(none))) ///
	groups(g_all = `"{bf:Full} {bf:Sample}"' g_white g_black g_hispanic = `"{bf:Race/} {bf:Ethnicity}"' ///
	g_frl g_nonfrl = `"{bf:NSLP} {bf:Eligibility}"' g_plengl g_plnoneng = `"{bf:Parent} {bf:Language}"' ///
	g_above_med_g3 g_below_med_g3 = `"{bf:3rd-Grade} {bf:Test} {bf:Scores}"'  ///
	g_above_med_sch_frl g_below_med_sch_frl = `"{bf:School} {bf:FRL}"' ///
	g_above_med_sch_zg5_m g_below_med_sch_zg5_m = `"{bf:School} {bf:Mean} {bf:Test} {bf:Score}"' ///
	, notick wrap(7) nobreak labs(vsmall) angle(0) labgap(*.25) ) ///
	coeflabels(g_all = `" "' g_white = `"White"' g_black = `"Black"' g_hispanic = "Hispanic" ///
	g_frl = `"Free Lunch"' g_nonfrl = `"Reduced/None"' g_plengl = `"English"' g_plnoneng = `"Non-English"' ///
	g_above_med_g3 = `"Above Median"' g_below_med_g3 = `"Below Median"' ///
	g_above_med_sch_frl = `"Above Median"' g_below_med_sch_frl = `"Below Median"' ///
	g_above_med_sch_zg5_m = `"Above Median"' g_below_med_sch_zg5_m = `"Below Median"', labsize(small) notick) ///
	ytick(none) ymtick(none) graphregion(color(white) fcolor(white) icolor(white) ifcolor(white) lcolor(white) ilcolor(white)) ///
	plotregion(color(white) fcolor(white) icolor(white) ifcolor(white) lcolor(white) ilcolor(white)) ///
	yscale(range(0 15.5)) ylabel(,labsize(*.8)) name(coefplot_hetero, replace)

graph display coefplot_hetero, ysize(4.75) xsize(7) scale(*1.1)
graph export "${out}fig_A5.png", replace
 
}

********************************************************************************
** FIG 8. GHA PARTICIPATION 
********************************************************************************
{
	use "${input}planb_rdsmpl.dta", clear
	barcompy0y1 gha 0 .2 1 trim
	graph display bar_gha, ysize() xsize() scale(*1.1)		
	graph export "${out}fig_8.png", replace
}

********************************************************************************
** FIG 9. REDUCED-FORM RELATIONSHIPS - ADVANCED COURSE SELECTION
********************************************************************************
{
	use "${input}planb_rdsmpl.dta", clear
	
	* sample flags for alternate figure titles in rdplot3bw 
	gen m_alt = m   
	gen f_alt = f
	* settings for axis labels 
	global gem6_set = "0 .2 .8 9.1"
	global alg8_set = "0 .2 1 9.1"
	global num_ap_course_set = "0 2 8 9.0"

	foreach sex in m f {
		foreach var of varlist gem6 alg8 num_ap_course {	
			rdplot3bw `var' `sex'_alt $`var'_set leg
			graph display `var'_`sex'_alt, ysize(2.6) xsize(3.75) scale(*1.4) 
			graph export "${out}fig_9_`var'_`sex'.png", replace
		}
	}
}

********************************************************************************
** FIG 10. REDUCED-FORM RELATIONSHIPS - MS SUSPENSIONS + HS GPA 
********************************************************************************
{
	use "${input}planb_rdsmpl.dta", clear

	* sample flags for alternate figure titles in rdplot3bw 
	gen m_alt = m   
	gen f_alt = f
	* settings for axis labels 
	global no_susp_ms_set = ".5 .1 1 9.2"	
	global math_gpa_hs_set = "2.5 .25 3.75 9.2"
	global gpa_hs_set = "2.75 .25 3.75 9.2"

	foreach sex in m f {
		foreach var of varlist no_susp_ms math_gpa_hs gpa_hs {	
			rdplot3bw `var' `sex'_alt $`var'_set leg
			graph display `var'_`sex'_alt, ysize(2.6) xsize(3.75) scale(*1.4) 
			graph export "${out}fig_10_`var'_`sex'.png", replace
		}
	}	
}

*******************************************************************************
** APP FIG A6. REDUCED-FORM RELATIONSHIPS - SURVEY (CHALLENGING COURSES)
********************************************************************************
{
	use "${input}planb_rdsmpl.dta", clear

	* sample flags for alternate figure titles in rdplot3bw 
	gen m_alt = m  
	gen f_alt = f	
	* settings for axis labels 
	global g6svy_set = "2.5 .5 5.0 9.1"
	global has_g6svy_set = ".3 .1 1 9.2"
	
	foreach sex in m f {
		foreach var of varlist g6svy has_g6svy {	
			rdplot3bw `var' `sex'_alt $`var'_set leg
			graph display `var'_`sex'_alt, ysize(2.7) xsize(3.8) scale(*1.3) 
			graph export "${out}fig_A6_`var'_`sex'.png", replace
		}
	}
}

********************************************************************************
** APP FIG A7. REDUCED-FORM RELATIONSHIPS - PEER QUALITY
********************************************************************************
{
	use "${input}planb_rdsmpl.dta", clear
	 rename peer_g35fcat_g68_math pq_ms_math
	 rename peer_g35fcat_g68_lang pq_ms_ela  
	 rename peer_g35fcat_hs_math pq_hs_math  
	 rename peer_g35fcat_hs_lang pq_hs_ela   
	
	* sample flags for alternate figure titles in rdplot3bw 
	gen m_alt = m  
	gen f_alt = f	
	* settings for axis labels 
	global pq_ms_math_set = "-.4 .2 1 9.2"
	global pq_ms_ela_set = "-.4 .2 1 9.2"
	global pq_hs_math_set = "-.4 .2 1 9.2"
	global pq_hs_ela_set = "-.4 .2 1 9.2"
	
	foreach sex in m f {
		foreach var of varlist pq_ms_math pq_ms_ela pq_hs_math pq_hs_ela {	
			rdplot3bw `var' `sex'_alt $`var'_set leg
			graph display `var'_`sex'_alt, ysize(2) xsize(3) scale(*1.5) 
			graph export "${out}fig_A7_`var'_`sex'.png", replace
		}
	}
}

********************************************************************************
** FIG 11. BAR CHART FIGURE WITH COMPLIER MEANS OF PEER QUALITY (MS & HS)
********************************************************************************
{
	use "${input}planb_rdsmpl.dta", clear
	 rename peer_g35fcat_g68_math pq_ms_math
	 rename peer_g35fcat_g68_lang pq_ms_ela  
	 rename peer_g35fcat_hs_math pq_hs_math  
	 rename peer_g35fcat_hs_lang pq_hs_ela  
	
	foreach sbj in ms_math ms_ela  {
		barcompy0y1 pq_`sbj' 0 .2 1 
		graph display bar_pq_`sbj', ysize(2.6) xsize(3.75) scale(*1.3)
		graph export "${out}fig_11_`sbj'.png", replace
	}
	foreach sbj in hs_math hs_ela {
		barcompy0y1 pq_`sbj' 0 .2 .8 
		graph display bar_pq_`sbj', ysize(2.6) xsize(3.75) scale(*1.3)
		graph export "${out}fig_11_`sbj'.png", replace
	}	
}
	
********************************************************************************
** FIG 12. REDUCED-FORM RELATIONSHIPS - TEST SCORES
********************************************************************************
{
	use "${input}planb_rdsmpl.dta", clear
	 rename fcat678_math fcatm 
	 rename fcat678_read fcatr 
	 rename maxpsatmathpct psatm
	 rename maxpsatreadpct psatv 
	
	* sample flags for alternate figure titles in rdplot3bw 
	gen m_alt = m  
	gen f_alt = f	
	* settings for axis labels 
	global fcatm_set = "-.5 .5 1.5 9.1"
	global fcatr_set = "-.5 .5 1.5 9.1"
	global psatm_set = "20 20 100 9.0"	
	global psatv_set = "20 20 100 9.0"	
	
	foreach sex in m f {
		foreach var of varlist fcatm fcatr psatm psatv {	
			rdplot3bw `var' `sex'_alt $`var'_set leg
			graph display `var'_`sex'_alt, ysize(2) xsize(3) scale(*1.4) 
			graph export "${out}fig_12_`var'_`sex'.png", replace
		}
	}
}


********************************************************************************
** APPENDIX B FIGS - MORE BAR CHARTS WITH MEAN POTENTIAL OUTCOMES 
** 					 FOR GIFTED & NON-GIFTED COMPLIERS BOYS & GIRLS
********************************************************************************
{
	
	********************************************************************************
	** FIG B1.  Middle School Math Course Enrollment
	********************************************************************************
	use "${input}planb_rdsmpl.dta", clear
		global gem6_set "0 .2 .6"
		global alg8_set ".2 .2 .8 "
		
		foreach dep in gem6 alg8  {
			barcompy0y1 `dep' ${`dep'_set} 
			graph display bar_`dep', ysize(3.2) xsize(4.4) scale(*1.3)
			graph export "${out}fig_B1_`dep'.png", replace
		}

	********************************************************************************
	** FIG B2. High School GPA
	********************************************************************************
	use "${input}planb_rdsmpl.dta", clear
		global math_gpa_hs_set "2.5 .5 4"
		global gpa_hs_set "3 .2 3.8"
		
		foreach dep in math_gpa_hs gpa_hs  {
			barcompy0y1 `dep' ${`dep'_set} 
			graph display bar_`dep', ysize(3.2) xsize(4.4) scale(*1.3)
			graph export "${out}fig_B2_`dep'.png", replace			
		}
		
	********************************************************************************
	** FIG B3. Survey Response on Guidance with Selecting Challenging Courses 
	********************************************************************************
	use "${input}planb_rdsmpl.dta", clear
		global g6svy_set "2 1 5"
		
		foreach dep in g6svy  {
			barcompy0y1 `dep' ${`dep'_set} 
			graph display bar_`dep', ysize(3.2) xsize(4.4) scale(*1.3)
			graph export "${out}fig_B3_`dep'.png", replace			
		}

	********************************************************************************
	** FIG B4. Other Non-Cog & Cog Outcomes 
	********************************************************************************
	use "${input}planb_rdsmpl.dta", clear
		rename fcat678_avgany fcat_ms 
		rename maxpsattotpct psat

		global no_susp_ms_set = ".5 .1 .9"	
		global num_ap_course_set = "0 2 6"
		global fcat_ms_set = "0 .3 1.5"
		global psat_set = "0 20 100"	

		foreach dep in no_susp_ms num_ap_course fcat_ms psat  {
			barcompy0y1 `dep' ${`dep'_set} 
			graph display bar_`dep', ysize(2.6) xsize(3.75) scale(*1.3)
			graph export "${out}fig_B4_`dep'.png", replace			
		}

}

	
********************************************************************************
** APPENDIX C - FIGURES for GHA ANALYSIS
********************************************************************************
********************************************************************************
*** APPENDIX FIG. C1: BAR CHARTS WITH COMPLIER MEANS (LOCAL LINEAR, BW=8)
*** Heterogeneity by gender & gifted share in GHA classroom
********************************************************************************
{
	use "${input}planb_rdsmpl.dta", clear
	cap drop hi lo 
	rename hipctgft hi 
	gen lo = 1-hi 
	
	foreach dep in gha collot {
		foreach smp in hi lo {
			gen `dep'_`smp' = `dep' if `smp'==1
			barcompy0y1 `dep'_`smp' 0 .25 1 trim
			graph display bar_`dep'_`smp', ysize(2.4) xsize(3.5) scale(*1.3)		
			graph export "${out}fig_C1_`dep'_`smp'.png", replace			
		}
	}	
}


********************************************************************************
** APPENDIX D - FIGURES for GEM ANALYSIS
********************************************************************************
*-------------------------------------------------------------------------------
* globals for bandwidths
*-------------------------------------------------------------------------------
global bw15 "inrange(gemr,-15,15)"
global bw20 "inrange(gemr,-20,20)" 
global bw25 "inrange(gemr,-25,25)" 	

********************************************************************************
** PROGRAM FOR GEM RD PLOTS 
********************************************************************************
cap program drop gemrdplot
program define gemrdplot
args dep smpl lb delta ub format leg

 /* program takes 7 arguments:
	dep: outcome 
	smpl: subgroup indicator (all=pooled, m=boys, f=girls, etc.)
	NOTE: smpl also sets figure subtitles; use m_alt, f_alt for titles without letters A/B
	lb, delta, ub: y-axis range 
	format: format of the y-axis label 
	leg: leg or noleg --> whether or not to include a legend
*/	

* set graph scheme 
set scheme modern 

preserve 
	* keep relevant sample (all, boys, girls)
	keep if `smpl'==1 

	* add fake obs 
	count 
	local n1 = `r(N)'+1
	set obs `n1'
	replace gemr=-.1 in `n1'

	* linear regressions for each bw
	forval bw=15(5)25 {
	    reg `dep' gemr gemd gemdxr if ${bw`bw'} 
		predict yhat_bw`bw' 
	}

	* means & se's by values of running variable
	bys gemr: egen mean=mean(`dep')
	bys gemr: egen sd=sd(`dep')
	bys gemr: egen n=count(`dep')
	gen se = sd/sqrt(n-1) 
	gen lower = mean-1.96*se 
	gen upper = mean+1.96*se

	* figure titles:
	if "`smpl'"=="all" {
			local title = ""
			}
	if "`smpl'"=="m" {
			local title = "A. Boys"
		}
	if "`smpl'"=="m_alt" {
			local title = "Boys"	
			}
	if "`smpl'"=="f" {
			local title = "B. Girls"
			}
	if "`smpl'"=="f_alt" {
			local title = "Girls"
		}
		
	* keep one observation by value of running variable 
	duplicates drop gemr, force 
	
	* construct figures with legend options:
	if "`leg'"=="leg" { 
		gen gemx = gemr+380 // rescaled running variable
		twoway ///
			(line yhat_bw25 gemx if ${bw25} & gemr<0, lc(red) lw(medthick)) ///
			(line yhat_bw20 gemx if ${bw20} & gemr<0, lc(green) lw(thick)) ///
			(line yhat_bw15 gemx if ${bw15} & gemr<0, lc(gold) lw(medthick)) ///	
			(line yhat_bw25 gemx if ${bw25} & gemr>=0, lc(red) lw(medthick)) ///
			(line yhat_bw20 gemx if ${bw20} & gemr>=0, lc(green) lw(thick)) ///
			(line yhat_bw15 gemx if ${bw15} & gemr>=0, lc(gold) lw(medthick)) ///	
			(scatter mean gemx, mc(blue) ms(o)) ///
			(rline lower upper gemx if gemr<0, fc(eltblue%20) lc(emidblue%80) lw(thin)) ///
			(rline lower upper gemx if gemr>=0, fc(eltblue%20) lc(emidblue%80) lw(thin)) ///
			, leg(order(1 "local linear, bw=25" 2 "local linear, bw=20" 3 "local linear, bw=15") r(3) ring(0) pos(10)) ///
			xline(380, lc(gs12) lw(medthick) lp("-")) xlabel(350 360 to 410, nogrid) ///
			ylabel(`lb'(`delta')`ub', angle(0) format(%`format'fc) axis(1) glcolor(gray*.15) glpattern(dash)) ///
			yti("") xti("5th-Grade Math Score") ti("`title'", size(*1.1)) name(`dep'_`smpl', replace)
	}	
	
restore	
end


********************************************************************************
** APPENDIX FIGS D1-D4. RD FOR EFFECTS OF GEM PARTICIPATION USING GR 5 MATH SCORE
********************************************************************************
{
	
use "${input}planb_rdsmpl.dta", clear
drop if cohort==2012	// because test used for running variable changed this year 
keep if inrange(gemr,-30,30) // GEM RD analysis sample (+/- 30 points of GEM eligibility threshold)
gen x = gemr+380 // rescaled running variable for figures
gen f_alt = f 
gen m_alt = m 

*-------------------------------------------------------------------------------
** FIG. D1.A. HISTOGRAM for GEM RD running variable (Grade 5 Math Score)
*-------------------------------------------------------------------------------
{
*- boys
graph twoway (hist x if m==1, freq xti("5th-Grade Math Score") start(350) w(5) ///
	fcolor(emidblue*0.6) lcolor(emidblue*0.8)) ///	
	(scatteri 0 380 200 380, c(l) m(i) lc(black*0.5) lp("dash")) ///
	, ylabel(, angle(0) format(%9.0fc) axis(1) glcolor(gray*.15) glpattern(dash)) ///
	xlab(350 360 to 410) ///
	graphregion(color(white) fcolor(white) icolor(white) ifcolor(white) lcolor(white) ilcolor(white)) ///
	plotregion(color(white) fcolor(white) icolor(white) ifcolor(white) lcolor(white) ilcolor(white)) ///
	legend(off) ti("Boys", size(*1.1)) name(gem_hist_m, replace)
	graph display gem_hist_m, ysize(2) xsize(3) scale(*1.2) 
	graph export "${out}fig_D1a_m.png", replace			
*- girls
graph twoway (hist x if f==1, freq xti("5th-Grade Math Score") start(350) w(5) ///
	fcolor(emidblue*0.6) lcolor(emidblue*0.8)) ///	
	(scatteri 0 380 200 380, c(l) m(i) lc(black*0.5) lp("dash")) ///
	, ylabel(, angle(0) format(%9.0fc) axis(1) glcolor(gray*.15) glpattern(dash)) ///
	xlab(350 360 to 410) ///
	graphregion(color(white) fcolor(white) icolor(white) ifcolor(white) lcolor(white) ilcolor(white)) ///
	plotregion(color(white) fcolor(white) icolor(white) ifcolor(white) lcolor(white) ilcolor(white)) ///
	legend(off) ti("Girls", size(*1.1)) name(gem_hist_f, replace)
	graph display gem_hist_f, ysize(2) xsize(3) scale(*1.2) 
	graph export "${out}fig_D1a_f.png", replace			
}
*-------------------------------------------------------------------------------
** FIG. D1.B. REDUCED-FORM RELATIONSHIPS - GEM PARTICIPATION
** FIG. D1.C. REDUCED-FORM RELATIONSHIPS - GIFTED BY 5TH GRADE
** FIG. D2. REDUCED-FORM RELATIONSHIPS - ON-TIME COLLEGE ENTRY
** FIG. D4.A. REDUCED-FORM RELATIONSHIPS - HS MATH GPA
** FIG. D4.B. REDUCED-FORM RELATIONSHIPS - # AP COURSES
*-------------------------------------------------------------------------------
* settings for axis labels 
	global gem6_set = "0 .2 1 9.2"
	global gifted_set = "0 .2 1 9.2"
	global collot_set = ".4 .1 1 9.2"
	global math_gpa_hs_set = "2.5 .25 3.75 9.2"
	global num_ap_course_set = "0 2 10 9.0"
	
* plots for D1 - panels b & c
	foreach var in gem6 gifted  {	
		foreach sex in m f {
			gemrdplot `var' `sex'_alt $`var'_set leg
			graph display `var'_`sex'_alt, ysize(2) xsize(3) scale(*1.2) 
			graph export "${out}fig_D1_`var'_`sex'.png", replace			
		}
	}
* plots for D2
	foreach var in collot {	
		foreach sex in m f {
			gemrdplot `var' `sex' $`var'_set leg
			graph display `var'_`sex', ysize(2) xsize(3) scale(*1.2) 
			graph export "${out}fig_D2_`var'_`sex'.png", replace			
		}
	}
* plots for D4
	foreach var in math_gpa_hs num_ap_course {	
		foreach sex in m f {
			gemrdplot `var' `sex'_alt $`var'_set leg
			graph display `var'_`sex'_alt, ysize(2) xsize(3) scale(*1.2) 
			graph export "${out}fig_D4_`var'_`sex'.png", replace			
		}
	}

	
*-------------------------------------------------------------------------------
** FIG. D3. VARY BANDWIDTH - ALL SYMMETRIC B/W FROM 5 to 30
*-------------------------------------------------------------------------------
{
				
	* make figure for each gender:		
	foreach smpl in m f {	

	* figure titles:
		if "`smpl'"=="m" {
				local title = "A. Boys"
			}
		if "`smpl'"=="f" {
				local title = "B. Girls"
				}	
		
		preserve 
		keep if `smpl'==1
		cap gen bw = .
		cap gen coeff = .
		cap gen se = .
		forval bw=5(1)30 {
			local upper = 380+`bw'
			local lower = 380-`bw'
			reg collot gemd gemr gemdxr if inrange(x,`lower',`upper')
			replace bw = `bw' in `bw'
			replace coeff = _b[gemd] in `bw'
			replace se = _se[gemd] in `bw'
		}
		gen cilo95 = coeff - 1.96*se 
		gen cihi95 = coeff + 1.96*se 
		gen cilo90 = coeff - 1.65*se 
		gen cihi90 = coeff + 1.65*se 
		
		twoway ///
			(rarea cilo90 cihi90 bw, lc(emidblue) fc(emidblue%20)) ///
			(rarea cilo95 cihi95 bw, lc(eltblue) fc(eltblue%20)) ///
			(scatter coeff bw) ///
			, yline(0) leg(order(3 "RD estimates" 1 "90% CI" 2 "95% CI") ring(0) pos(4)) ///
			xti("bandwidth (5th-Grade Math Score)") ti("`title'", size(*1.1)) ///
			name(figd3_`smpl', replace)
			
	restore		
	}
}

	graph display figd3_m, ysize(2.33) xsize(3.5) scale(*1.2) 
			graph export "${out}fig_D3a.png", replace			
	graph display figd3_f, ysize(2.33) xsize(3.5) scale(*1.2) 
			graph export "${out}fig_D3b.png", replace			

}
